<template>
  <div class="points-approval">
    <div class="page-header">
      <h2>积分流程审批</h2>
      <div class="header-actions">
        <el-button @click="loadData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="待我审批" name="pending">
        <div class="tab-content">
          <!-- 搜索筛选 -->
          <div class="search-form">
            <el-form :model="searchForm" inline>
              <el-form-item label="部门">
                <el-select v-model="searchForm.departmentId" placeholder="请选择部门" clearable>
                  <el-option
                    v-for="dept in departments"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="积分类型">
                <el-select v-model="searchForm.pointsType" placeholder="请选择类型" clearable>
                  <el-option label="加分" value="add" />
                  <el-option label="扣分" value="deduct" />
                </el-select>
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="searchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="请输入事件描述或责任人"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 待审批列表 -->
          <div class="table-container">
            <el-table
              v-loading="loading"
              :data="pendingList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="record.recordTime" label="记录时间" width="160" />
              <el-table-column prop="record.departmentName" label="部门" width="120" />
              <el-table-column prop="record.responsiblePersonName" label="责任人" width="100" />
              <el-table-column prop="record.eventDescription" label="事件描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="record.pointsType" label="积分类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.record.pointsType === 'add' ? 'success' : 'danger'">
                    {{ row.record.pointsType === 'add' ? '加分' : '扣分' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="record.pointsValue" label="积分分值" width="100">
                <template #default="{ row }">
                  <span :class="row.record.pointsType === 'add' ? 'text-success' : 'text-danger'">
                    {{ row.record.pointsType === 'add' ? '+' : '-' }}{{ row.record.pointsValue }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="record.recorderName" label="记录人" width="100" />
              <el-table-column prop="createTime" label="申请时间" width="160" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewDetail(row)">
                    查看详情
                  </el-button>
                  <el-button type="success" size="small" @click="approveRecord(row, 'approved')">
                    同意
                  </el-button>
                  <el-button type="danger" size="small" @click="approveRecord(row, 'rejected')">
                    拒绝
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.page"
                v-model:page-size="pagination.pageSize"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="我的审批" name="my">
        <div class="tab-content">
          <!-- 我的审批列表 -->
          <div class="table-container">
            <el-table
              v-loading="loading"
              :data="myApprovalsList"
              stripe
              border
              style="width: 100%"
            >
              <el-table-column prop="record.recordTime" label="记录时间" width="160" />
              <el-table-column prop="record.departmentName" label="部门" width="120" />
              <el-table-column prop="record.responsiblePersonName" label="责任人" width="100" />
              <el-table-column prop="record.eventDescription" label="事件描述" min-width="200" show-overflow-tooltip />
              <el-table-column prop="record.pointsType" label="积分类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.record.pointsType === 'add' ? 'success' : 'danger'">
                    {{ row.record.pointsType === 'add' ? '加分' : '扣分' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="record.pointsValue" label="积分分值" width="100">
                <template #default="{ row }">
                  <span :class="row.record.pointsType === 'add' ? 'text-success' : 'text-danger'">
                    {{ row.record.pointsType === 'add' ? '+' : '-' }}{{ row.record.pointsValue }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="approvalStatus" label="审批状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getApprovalStatusType(row.approvalStatus)">
                    {{ getApprovalStatusText(row.approvalStatus) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="approvalTime" label="审批时间" width="160" />
              <el-table-column prop="approvalComment" label="审批意见" min-width="150" show-overflow-tooltip />
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="viewDetail(row)">
                    查看详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="myPagination.page"
                v-model:page-size="myPagination.pageSize"
                :total="myPagination.total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleMySizeChange"
                @current-change="handleMyCurrentChange"
              />
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="积分记录详情"
      width="800px"
    >
      <div v-if="currentApproval" class="approval-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录时间">
            {{ currentApproval.record.recordTime }}
          </el-descriptions-item>
          <el-descriptions-item label="部门">
            {{ currentApproval.record.departmentName }}
          </el-descriptions-item>
          <el-descriptions-item label="责任人">
            {{ currentApproval.record.responsiblePersonName }}
          </el-descriptions-item>
          <el-descriptions-item label="记录人">
            {{ currentApproval.record.recorderName }}
          </el-descriptions-item>
          <el-descriptions-item label="积分类型">
            <el-tag :type="currentApproval.record.pointsType === 'add' ? 'success' : 'danger'">
              {{ currentApproval.record.pointsType === 'add' ? '加分' : '扣分' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="积分分值">
            <span :class="currentApproval.record.pointsType === 'add' ? 'text-success' : 'text-danger'">
              {{ currentApproval.record.pointsType === 'add' ? '+' : '-' }}{{ currentApproval.record.pointsValue }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="审批状态">
            <el-tag :type="getApprovalStatusType(currentApproval.approvalStatus)">
              {{ getApprovalStatusText(currentApproval.approvalStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ currentApproval.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="地点">
            {{ currentApproval.record.location || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-tag :type="getSeverityType(currentApproval.record.severity)">
              {{ getSeverityText(currentApproval.record.severity) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="event-description">
          <h4>事件描述</h4>
          <p>{{ currentApproval.record.eventDescription }}</p>
        </div>
        
        <div v-if="currentApproval.record.attachments && currentApproval.record.attachments.length" class="attachments">
          <h4>附件</h4>
          <div class="attachment-list">
            <div
              v-for="(attachment, index) in currentApproval.record.attachments"
              :key="index"
              class="attachment-item"
            >
              <el-image
                v-if="isImage(attachment)"
                :src="attachment"
                :preview-src-list="currentApproval.record.attachments"
                style="width: 100px; height: 100px"
                fit="cover"
              />
              <div v-else class="file-item">
                <el-icon><Document /></el-icon>
                <span>{{ getFileName(attachment) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      :title="approvalAction === 'approved' ? '同意审批' : '拒绝审批'"
      width="600px"
    >
      <el-form :model="approvalForm" label-width="100px">
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            :rows="4"
            :placeholder="approvalAction === 'approved' ? '请输入同意理由（可选）' : '请输入拒绝理由'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button 
          :type="approvalAction === 'approved' ? 'success' : 'danger'"
          @click="handleApproval"
          :loading="approving"
        >
          {{ approvalAction === 'approved' ? '同意' : '拒绝' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Search, Document } from '@element-plus/icons-vue'
import type { PointsApproval } from '@/types/points'

// 响应式数据
const loading = ref(false)
const approving = ref(false)
const activeTab = ref('pending')
const pendingList = ref<PointsApproval[]>([])
const myApprovalsList = ref<PointsApproval[]>([])
const currentApproval = ref<PointsApproval | null>(null)
const departments = ref([
  { id: '1', name: '安全部' },
  { id: '2', name: '生产部' },
  { id: '3', name: '技术部' },
  { id: '4', name: '质量部' }
])

// 对话框状态
const detailDialogVisible = ref(false)
const approvalDialogVisible = ref(false)
const approvalAction = ref<'approved' | 'rejected'>('approved')
const currentApprovalId = ref('')

// 搜索表单
const searchForm = reactive({
  departmentId: '',
  pointsType: '',
  dateRange: [],
  keyword: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const myPagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 审批表单
const approvalForm = reactive({
  comment: ''
})

// 模拟数据
const mockPendingData: PointsApproval[] = [
  {
    id: '1',
    recordId: 'r1',
    record: {
      id: 'r1',
      departmentId: '1',
      departmentName: '安全部',
      responsiblePersonId: 'u1',
      responsiblePersonName: '张三',
      eventDescription: '发现员工未佩戴安全帽进入施工现场',
      pointsType: 'deduct',
      pointsValue: 5,
      attachments: [],
      recorderId: 'u2',
      recorderName: '李四',
      recordTime: '2024-01-15 09:30:00',
      status: 'pending',
      location: 'A区施工现场',
      severity: 'medium'
    },
    approverId: 'u3',
    approverName: '王五',
    approvalStatus: 'pending',
    createTime: '2024-01-15 09:35:00',
    updateTime: '2024-01-15 09:35:00'
  },
  {
    id: '2',
    recordId: 'r2',
    record: {
      id: 'r2',
      departmentId: '2',
      departmentName: '生产部',
      responsiblePersonId: 'u4',
      responsiblePersonName: '赵六',
      eventDescription: '主动发现并报告安全隐患，避免事故发生',
      pointsType: 'add',
      pointsValue: 10,
      attachments: [],
      recorderId: 'u5',
      recorderName: '孙七',
      recordTime: '2024-01-15 14:20:00',
      status: 'pending',
      location: 'B车间',
      severity: 'high'
    },
    approverId: 'u3',
    approverName: '王五',
    approvalStatus: 'pending',
    createTime: '2024-01-15 14:25:00',
    updateTime: '2024-01-15 14:25:00'
  }
]

const mockMyApprovalsData: PointsApproval[] = [
  {
    id: '3',
    recordId: 'r3',
    record: {
      id: 'r3',
      departmentId: '1',
      departmentName: '安全部',
      responsiblePersonId: 'u6',
      responsiblePersonName: '周八',
      eventDescription: '未按规定进行安全交底',
      pointsType: 'deduct',
      pointsValue: 3,
      attachments: [],
      recorderId: 'u7',
      recorderName: '吴九',
      recordTime: '2024-01-14 16:45:00',
      status: 'approved',
      location: 'C区施工现场',
      severity: 'low'
    },
    approverId: 'u3',
    approverName: '王五',
    approvalStatus: 'approved',
    approvalTime: '2024-01-14 17:00:00',
    approvalComment: '同意扣分，请加强安全交底工作',
    createTime: '2024-01-14 16:50:00',
    updateTime: '2024-01-14 17:00:00'
  },
  {
    id: '4',
    recordId: 'r4',
    record: {
      id: 'r4',
      departmentId: '3',
      departmentName: '技术部',
      responsiblePersonId: 'u8',
      responsiblePersonName: '郑十',
      eventDescription: '违规操作设备，存在安全隐患',
      pointsType: 'deduct',
      pointsValue: 8,
      attachments: [],
      recorderId: 'u9',
      recorderName: '冯十一',
      recordTime: '2024-01-13 11:15:00',
      status: 'rejected',
      location: 'D车间',
      severity: 'high'
    },
    approverId: 'u3',
    approverName: '王五',
    approvalStatus: 'rejected',
    approvalTime: '2024-01-13 11:30:00',
    approvalComment: '证据不足，需要进一步核实',
    createTime: '2024-01-13 11:20:00',
    updateTime: '2024-01-13 11:30:00'
  }
]

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (activeTab.value === 'pending') {
      pendingList.value = mockPendingData
      pagination.total = mockPendingData.length
    } else {
      myApprovalsList.value = mockMyApprovalsData
      myPagination.total = mockMyApprovalsData.length
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleTabChange = (tab: string) => {
  activeTab.value = tab
  loadData()
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    departmentId: '',
    pointsType: '',
    dateRange: [],
    keyword: ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleMySizeChange = (size: number) => {
  myPagination.pageSize = size
  myPagination.page = 1
  loadData()
}

const handleMyCurrentChange = (page: number) => {
  myPagination.page = page
  loadData()
}

const viewDetail = (row: PointsApproval) => {
  currentApproval.value = row
  detailDialogVisible.value = true
}

const approveRecord = (row: PointsApproval, action: 'approved' | 'rejected') => {
  currentApprovalId.value = row.id
  approvalAction.value = action
  approvalForm.comment = ''
  approvalDialogVisible.value = true
}

const handleApproval = async () => {
  if (approvalAction.value === 'rejected' && !approvalForm.comment.trim()) {
    ElMessage.warning('拒绝审批时必须填写拒绝理由')
    return
  }
  
  approving.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(approvalAction.value === 'approved' ? '审批通过' : '审批拒绝')
    approvalDialogVisible.value = false
    
    // 更新本地数据
    const index = pendingList.value.findIndex(item => item.id === currentApprovalId.value)
    if (index !== -1) {
      pendingList.value[index].approvalStatus = approvalAction.value
      pendingList.value[index].approvalTime = new Date().toLocaleString()
      pendingList.value[index].approvalComment = approvalForm.comment
    }
    
    loadData()
  } catch (error) {
    ElMessage.error('审批失败')
  } finally {
    approving.value = false
  }
}

// 工具方法
const getApprovalStatusType = (status: string) => {
  const statusMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

const getApprovalStatusText = (status: string) => {
  const statusMap = {
    pending: '待审批',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

const getSeverityType = (severity: string) => {
  const severityMap = {
    low: 'success',
    medium: 'warning',
    high: 'danger'
  }
  return severityMap[severity] || 'info'
}

const getSeverityText = (severity: string) => {
  const severityMap = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return severityMap[severity] || severity
}

const isImage = (url: string) => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url)
}

const getFileName = (url: string) => {
  return url.split('/').pop() || url
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.points-approval {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .tab-content {
    .search-form {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .table-container {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      
      .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
  
  .text-success {
    color: #67c23a;
    font-weight: bold;
  }
  
  .text-danger {
    color: #f56c6c;
    font-weight: bold;
  }
  
  .approval-detail {
    .event-description {
      margin: 20px 0;
      
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
      
      p {
        line-height: 1.6;
        color: #606266;
      }
    }
    
    .attachments {
      margin-top: 20px;
      
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
      
      .attachment-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        
        .attachment-item {
          .file-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            background: #f5f7fa;
          }
        }
      }
    }
  }
}
</style>
